import { useEffect, useRef } from "react";
import {
    ArcRotateCamera, Color4, Engine, HemisphericLight, Mesh, MeshBuilder, Plane, Scene, UniversalCamera,
    StandardMaterial, Vector3, Color3, DirectionalLight, Animation, CircleEase, EasingFunction, VertexBuffer,
} from '@babylonjs/core';
import Play from '../component/Player';


const canvas = document.createElement("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const engine = new Engine(canvas, true);
const scene = new Scene(engine);


const camera = new UniversalCamera('Camera', new Vector3(0, 0, 10), scene);
camera.setTarget(new Vector3(0, 0, 0));
camera.attachControl(canvas, true);

const play = new Play(camera);
play.start();

const updateAction: ((time: number) => {})[] = [];

const light = new HemisphericLight('pxg', new Vector3(1, 1, 0), scene);
const ground = MeshBuilder.CreateGround('ground', { width: 8, height: 8, updatable: true }, scene);
ground.rotation.x = Math.PI / 2;
ground.position.z = -1;





function main() {
    let index = 0;
    window.addEventListener("click", function () {
        var pickResult = scene.pick(scene.pointerX, scene.pointerY);

        console.log(pickResult)

        if (pickResult.pickedPoint != null) {
            const box = MeshBuilder.CreateBox(`box${index++}`, {
                width: 0.1, height: 0.1, depth: 0.1, faceColors: [
                    new Color4(1, 0, 0, 1),
                    new Color4(1, 0, 0, 1),
                    new Color4(1, 0, 0, 1),
                    new Color4(1, 0, 0, 1),
                    new Color4(1, 0, 0, 1),
                    new Color4(1, 0, 0, 1),
                ]
            }, scene);
            box.position.copyFrom(pickResult.pickedPoint);

            //获得选择物体上选择三角形的三个顶点
            var elements = pickResult.pickedMesh!.getIndices()!;
            var index0 = elements[pickResult.faceId * 3];
            var index1 = elements[pickResult.faceId * 3 + 1];
            var index2 = elements[pickResult.faceId * 3 + 2];

            //console.log(pickResult.pickedMesh?.getVerticesData(VertexBuffer.PositionKind))
        }
    });
}







const RenderStructure = () => {
    const divRef = useRef<HTMLDivElement>(null);
    useEffect(() => {
        const { current } = divRef;
        if (current != null) {
            current.innerHTML = '';
            current.append(canvas);
            ani(0);
            main();
        }
    }, []);
    return (
        <div ref={divRef}></div>
    );
};

export default RenderStructure;

function ani(time: number) {
    updateAction.forEach((action) => {
        action(time);
    })
    scene.render();

    requestAnimationFrame(ani);
};